//
//  ViewController.m
//
//  Copyright 2012 Google Inc.
//
//  Licensed under the Apache License, Version 2.0 (the "License"); you may not
//  use this file except in compliance with the License.  You may obtain a copy
//  of the License at
//
//  http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
//  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
//  License for the specific language governing permissions and limitations under
//  the License.
//

#import "SearchViewController.h"

#import "GTLQueryShopping.h"
#import "GTLShopping.h"
#import "ResultsViewController.h"

@implementation SearchViewController

@synthesize searchTextField = _searchTextField;
@synthesize products = _products;

static NSString * const kAPIKey = @"YOUR_API_KEY";

// The user pressed search, so query the API.
- (IBAction) didTapSearch:(id)sender {
  
  // Set up the service to call the shopping API.
  GTLServiceShopping *shoppingService = [[GTLServiceShopping alloc] init];
  shoppingService.retryEnabled = YES;
  shoppingService.APIKey = kAPIKey;
  
  // Construct the query based upon the text field.
  GTLQueryShopping *query = [GTLQueryShopping
                               queryForProductsListWithSource:@"public"];
  query.q = [_searchTextField text];
  query.country = @"US";
  
  // Execute the query and perform the segue.
  [shoppingService executeQuery:query
              completionHandler:^(GTLServiceTicket *ticket,
                                  id object,
                                  NSError *error) {
                  if (error) {
                    NSLog(@"Something went wrong: %@", error);
                  } else {
                    // We got results, so populate our products.
                    self.products = object;
                    [self performSegueWithIdentifier:@"SearchSegue"
                                              sender:sender];
                  }
               }];
}

// This hides the keyboard and start the search
- (BOOL)textFieldShouldReturn:(UITextField *)theTextField {
  [theTextField resignFirstResponder];
  return YES;
}

// Handle the SearchViewController's segues.
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
  if ([[segue identifier] isEqualToString:@"SearchSegue"]) {
    // Set up the view controller.
    ResultsViewController *vc = [segue destinationViewController];
    
    // Set up the data source for the table.
    [vc setDataSource:_products];
  }
}

@end
